package com.chatai.controller;

import com.chatai.dto.UserLoginDTO;
import com.chatai.dto.UserRegisterDTO;
import com.chatai.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
    
    @Autowired
    private AuthService authService;
    
    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@Validated @RequestBody UserRegisterDTO registerDTO) {
        logger.info("收到注册请求: username={}, email={}", registerDTO.getUsername(), registerDTO.getEmail());
        try {
            logger.debug("调用AuthService.register方法");
            Map<String, Object> response = authService.register(registerDTO);
            boolean success = Boolean.TRUE.equals(response.getOrDefault("success", false));
            if (success) {
                logger.info("注册成功: username={}", registerDTO.getUsername());
                return ResponseEntity.ok(response);
            } else {
                logger.warn("注册失败: username={}, message={}", registerDTO.getUsername(), response.get("message"));
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }
        } catch (Exception e) {
            logger.error("注册过程中发生异常: username={}, error={}", registerDTO.getUsername(), e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "注册过程中发生错误: " + e.getMessage());
            errorResponse.put("error", "registration_exception");
            errorResponse.put("exception_type", e.getClass().getName());
            errorResponse.put("exception_message", e.getMessage());
            
            // 添加堆栈跟踪的简要信息
            String stackTrace = getStackTraceSummary(e);
            errorResponse.put("stack_trace_summary", stackTrace);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody UserLoginDTO loginDTO) {
        System.out.println("[AuthController] 收到登录请求，开始处理...");
        try {
            System.out.println("[AuthController] 登录请求参数: username=" + (loginDTO != null ? loginDTO.getUsername() : "null"));
            
            if (loginDTO == null) {
                System.out.println("[AuthController] 错误: loginDTO为null");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "请求参数为空");
                errorResponse.put("error", "empty_request");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
            }
            
            if (loginDTO.getUsername() == null || loginDTO.getPassword() == null) {
                System.out.println("[AuthController] 错误: 用户名或密码为空");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "用户名或密码不能为空");
                errorResponse.put("error", "missing_credentials");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
            }
            
            System.out.println("[AuthController] 调用AuthService.login方法");
            Map<String, Object> response = authService.login(loginDTO);
            
            System.out.println("[AuthController] AuthService返回结果: response=" + response);
            
            if (response == null) {
                System.out.println("[AuthController] 错误: AuthService返回null");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "服务响应异常");
                errorResponse.put("error", "null_response");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
            }
            
            boolean success = Boolean.TRUE.equals(response.getOrDefault("success", false));
            if (success) {
                System.out.println("[AuthController] 登录成功: username=" + loginDTO.getUsername());
                return ResponseEntity.ok(response);
            } else {
                System.out.println("[AuthController] 登录失败: username=" + loginDTO.getUsername() + ", message=" + response.get("message"));
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
        } catch (Exception e) {
            System.out.println("[AuthController] 登录过程中发生异常: " + e.getMessage());
            System.out.println("[AuthController] 异常类型: " + e.getClass().getName());
            System.out.println("[AuthController] 异常堆栈:");
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "登录过程中发生错误: " + e.getMessage());
            errorResponse.put("error", "login_exception");
            errorResponse.put("exception_type", e.getClass().getName());
            errorResponse.put("exception_message", e.getMessage());
            
            // 添加堆栈跟踪的简要信息
            String stackTrace = getStackTraceSummary(e);
            errorResponse.put("stack_trace_summary", stackTrace);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        } finally {
            System.out.println("[AuthController] 登录请求处理结束");
        }
    }
    
    // 获取当前用户信息
    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser() {
        logger.info("收到获取当前用户信息请求");
        try {
            logger.debug("调用AuthService.getCurrentUser方法");
            Map<String, Object> response = new HashMap<>();
            response.put("user", authService.getCurrentUser());
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取当前用户信息过程中发生异常: error={}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取用户信息失败: " + e.getMessage());
            errorResponse.put("error", "get_user_exception");
            errorResponse.put("exception_type", e.getClass().getName());
            errorResponse.put("exception_message", e.getMessage());
            
            // 添加堆栈跟踪的简要信息
            String stackTrace = getStackTraceSummary(e);
            errorResponse.put("stack_trace_summary", stackTrace);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    // 获取堆栈跟踪的简要信息
    private String getStackTraceSummary(Exception e) {
        StringBuilder stackTrace = new StringBuilder();
        StackTraceElement[] elements = e.getStackTrace();
        // 只获取前5行堆栈信息
        int limit = Math.min(5, elements.length);
        for (int i = 0; i < limit; i++) {
            stackTrace.append(elements[i].toString()).append("\n");
        }
        return stackTrace.toString();
    }
    
    // 用户退出登录
    @PostMapping("/logout")
    public Map<String, Object> logout() {
        // 最简单的实现，直接返回Map对象，不涉及ResponseEntity
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "退出登录成功");
        return response;
    }
}